<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 手机短信接口
 */
class Myshoplazza extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;
    protected $iscustom = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionordershoplaza;
        $this->iscustom['apikey'] = 'waitingnowg@gmail.com';
        $this->iscustom['secretapikey'] = '3084065C-C38B-2C3A-A4C0-E11C09316545';
    }

    //Oauth 触发接口app_uri
    //http://zhtest.dnssystem.cn/api/Myshoplazza/app_uri
    public function app_uri()
    {
        $api_key = '';
        $scopes = 'read_product write_product read_order write_order read_collection write_collection read_shop read_comments write_comments read_script_tags write_script_tags read_customer write_customer read_app_proxy write_app_proxy read_price_rules write_price_rules read_data write_data';
        $redirect_uri = 'http://zhtest.dnssystem.cn/api/Myshoplazza/redirect_uri';
        $response_type = 'code';
        $url = 'https://dj-03.myshoplaza.com/admin/oauth/authorize?client_id='.$api_key.'&scope='.$scopes.'&redirect_uri='.$redirect_uri.'&response_type='.$response_type;
        header("location: ".$url);die;
    }

    //Oauth回调接口 redirect_uri
//Oauth 触发接口 http://121.5.76.151:100/api/Myshoplazza/app_uri
//Oauth回调接口 http://121.5.76.151:100/api/Myshoplazza/redirect_uri
    public function redirect_uri()
    {
        $this->success('返回数据');
    }

    /**
     * 后台自动获取数据
     * $type 1 拉取所有订单
     * $type 2 实时拉取当下订单
     * $type 3 拉取之前的订单
     */
    public function accounturl_iscustom()
    {
        $type = $this->request->request('type');

        $accounturl = $this->request->request('accounturl');
        if (!empty($accounturl)) {
            $where['id'] = $accounturl;
        }else{
            //从56店铺开始更新
            $where['id']  = array('egt',73);
        }

        $result = array();
        if(!empty($type)){
            $iscustom = Db::name('fedition_accounturl')
                ->where('iscustom_shoplaza',1)
                ->where('status','normal')
                ->where($where)
                ->select();
            if($iscustom){
                foreach ($iscustom as $k => $v) {
                    $result[] = $this->orders($v,$type);
                }
            }
        }
        $this->success('操作成功',$result);
    }

    public function orderinfo()
    {
        $iscustom = Db::name('fedition_accounturl')
            ->where('iscustom_shoplaza',1)
            ->where('status','normal')
            ->where('id','39')
            ->find();
        $url = $iscustom['shoplazaname']."/openapi/2020-07/orders/261312-KCO90396";
        $data = $this->geturl($url,$iscustom['shoplazatoken']);

        $data = json_decode($data,true);
        dump($data);
        die;
    }

    /**
     * orders
     * order payment status订单付款状态: waiting等待, paying付款, paid已付款, cancelled取消, failed失败, refunding退款, refund_failed退款失败, refunded退款, partially_refunded部分退款
     * payment method付款方法 (cod鳕鱼, online在线 , none无)
     * 物流状态fulfillment_status：初始initialled、等待waiting、部分发货partially_shipped、已发货shipped、部分完成partially_finished、完成finished、取消cancelled、退货returning、退回returned
     */
    public function orders($iscustom,$type)
    {
        $limit = '250';
        $url = $iscustom['shoplazaname']."/openapi/2020-07/orders";
        if($type == 3){
            //拉取之前的订单
            $before_ordershopify = Db::name('fedition_ordershoplaza')
                ->where('accounturl',$iscustom['id'])
                ->order('ycreated_at asc')
                ->find();
            if($before_ordershopify){
                $created_at_max = $before_ordershopify['ycreated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1.'T'.$created_at_max2.'-04:00';
            }
            //拉取之前的订单
            $url = $url.'?created_at_max='.$created_at_max;
        }
        if($type == 2){
            $last_ordershopify = Db::name('fedition_ordershoplaza')
                ->where('accounturl',$iscustom['id'])
                ->order('yupdated_at desc')
                ->find();
            if($last_ordershopify){
                $updated_at_min = $last_ordershopify['yupdated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url.'?updated_at_min='.$updated_at_min;
        }
        if($type == 1){
            $url = $url.'?limit='.$limit;
        }else{
            $url = $url.'&limit='.$limit;
        }
        $data = $this->geturl($url,$iscustom['shoplazatoken']);
        $result = 0;
        if($data){
            $data = json_decode($data,true);
            if ($data == 'Unauthorized') {
                return '未经授权';
            }
            $orders = array();
            if(isset($data['orders'])){
                $orders = $data['orders'];
            }
            if(is_array($orders) && !empty($orders)){
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as $k => $v) {
                    $row = $this->model->get($v['id']);
                    $arr['id'] = $v['id'];
                    $arr['number'] = $v['number'];
                    //美国时间转北京时间
                    $arr['ycreated_at'] = $v['created_at'];
                    $arr['yupdated_at'] = $v['updated_at'];
                    //店匠显示国内时间
                    $arr['created_at'] = strtotime($v['created_at']);
                    $arr['updated_at'] = strtotime($v['updated_at']);
                    $arr['currency'] = $v['currency'];
                    if (!empty($v['financial_status'])) {
                        $arr['financial_status'] = $v['financial_status'];
                    } else {
                        $arr['financial_status'] = 'unfulfilled';
                    }
                    //加字段
                    if (!empty($v['payment_line']) && isset($v['payment_line']['transaction_no'])) {
                        $arr['transaction_no'] = $v['payment_line']['transaction_no'];
                    }
//                    运费
//                    $arr['freight'] = $v['total_shipping'];
//                    $arr['freightmj'] = number_format((float)$arr['freight'] / 6.453, 3);
                    $arr['ytotal_price'] = $v['total_price'];
                    $arr['total_price'] = $v['total_price'] - $v['total_refund_price']; //减去总退款金额
                    if ($arr['financial_status'] == 'refunded') {
                        $arr['total_price'] = 0;
                    }
                    $arr['accounturl'] = $iscustom['id'];
                    $arr['gateway'] = $v['payment_method'];
                    $arr['fulfillment_status'] = $v['fulfillment_status'];
                    $arr['refund_status'] = $v['refund_status'];
                    if($row){
                        if($row['yupdated_at'] !== $arr['yupdated_at']){
                            $result = $row->save($arr);
                            $this->ordershoplazasms($v,2);
                        }else{
                            $result = '重复';
                        }
                    }else{
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = $this->model->insert($arr);
                        $this->ordershoplazasms($v,1);
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 新增采购成本
     */
    public function addmaterial($id = null)
    {
        if (!empty($id)) {
            $ordershopify = Db::name('fedition_ordershoplaza')->where('id',$id)->select();
        }else{
            $type = $this->request->request('type');

            //加入只操作上个月的限制
//            $where_created = array();
//            $created_star = '1630425600';
//            $created_end = '1633017599';
//            $where_created['created_at'] = array(array('egt',$created_star),array('elt',$created_end));

            $ordershopify = Db::name('fedition_ordershoplaza')
                ->where('ismaterial',$type)
//                ->where($where_created)
                ->order('materialtime asc')
                ->limit(200)->select();
        }
        if (!empty($ordershopify)) {
            foreach ($ordershopify as $item) {
                $shopify = $this->add_material($item);
            }
            $this->success('操作成功',$shopify);
        } else {
            $this->error('未找到相关订单');
        }
    }

    public function add_material($ordershopify)
    {
        $orderquantity = Db::name('fedition_orderquantityp')->where('order_id',$ordershopify['id'])->select();
        $material = 0;
        if (!empty($orderquantity)) {
            foreach ($orderquantity as $item) {
                $orderproductp = Db::name('fedition_orderproductp')
                    ->where('product_id',$item['product_id'])
                    ->find();
                if (!empty($orderproductp)) {
                    $newmaterial = $orderproductp['material'] * $item['quantity'];
                    $material = $material + $newmaterial;
                }
            }
        }
        $data['material'] = $material;
        $data['materialtime'] = time();
        if (!empty($data['material'])) {
            $data['ismaterial'] = 1;
        }else{
            $data['ismaterial'] = 3;
        }
        $shopify = Db::name('fedition_ordershoplaza')->where('id',$ordershopify['id'])->update($data);
        return $shopify;
    }

    /**
     * add_reportmonth 统计上个月利润
     * $type 1 上个月
     * 2 上上个月
     * 3 指定时间戳月份 传开始时间戳
     */
    public function add_reportmonth($id = null)
    {
        $where2 = '1=1';
        $type = $this->request->request('type');
        $timedate = 'created_at';
        if (!empty($id)) {
            $reportmonth = Db::name('fedition_reportmonthp')->where('id',$id)->find();
            if (!empty($reportmonth)) {
                $where2 = " accounturl = '".$reportmonth['accounturl']."' ";
                $lastmonth_start = $reportmonth['timedate'];
                $lastmonth_end = mktime(23,59,59,date('m',$reportmonth['timedate']),date('t',$reportmonth['timedate']),date('Y',$reportmonth['timedate']));
            } else {
                $this->error('参数错误，请重新登录');
            }
        }else{
            if ($type == 1) {
                $lastmonth_start=mktime(0,0,0,date('m')-1,1,date('Y'));
                $lastmonth_end=mktime(23,59,59,date('m'),0,date('Y'));
            } elseif ($type == 2) {
                $lastmonth_start=mktime(0,0,0,date('m')-2,1,date('Y'));
                $lastmonth_end=mktime(23,59,59,date('m')-1,0,date('Y'));
            }else {
                $lastmonth_start=mktime(0,0,0,date('m')-1,1,date('Y'));
                $lastmonth_end=mktime(23,59,59,date('m'),0,date('Y'));
            }
        }
        $times = $timedate.'>='.$lastmonth_start.' and '.$timedate.'<='.$lastmonth_end;
        $sql = "SELECT accounturl
,cast(sum(total_price) AS decimal(15,2)) as total_price
,cast(sum(freight) AS decimal(15,2)) as freight
,cast(sum(freightmj) AS decimal(15,2)) as freightmj
,cast(sum(material) AS decimal(15,2)) as material
FROM fa_fedition_ordershoplaza
WHERE ".$times."
AND ".$where2."
AND (financial_status = 'paid' or financial_status = 'partially_refunded')
AND (fulfillment_status = 'finished' or fulfillment_status = 'shipped')
GROUP BY accounturl
ORDER BY accounturl ASC";
        $statistics = \think\Db::query($sql);
        $reportmonth = array();
        foreach ($statistics as $item) {
            $arr['createtime'] = time();
            $arr['updatetime'] = time();
            $arr['freight'] = $item['freight'];
            $arr['freightmj'] = $item['freightmj'];

            //实时汇率接口未开发
            if (!empty($item['material'])) {
                $arr['materialrmb'] = (float)$item['material'];
//                $arr['material'] = number_format((float)$item['material'] / 6.3, 3);
                $arr['material'] = $item['material'] / 6.3;
                $arr['material'] = (float)$arr['material'];
            } else {
                $arr['material'] = 0;
            }

            //计算个人填写的广告消耗
            $accounturl = Db::name('fedition_accounturl')->where('id',$item['accounturl'])->find();
            if (!empty($accounturl)) {
                $arr['admin_id'] = $accounturl['admin_id'];
            } else {
                $arr['admin_id'] = '';
            }

            $arr['advertisingz'] = 0;
            $arr['zcost'] = (float)$arr['material'] + (float)$arr['freightmj'] + (float)$arr['advertisingz'];

            //销售额
            $arr['salesz'] = $item['total_price'];
            $arr['salesz_discount'] = $arr['salesz'] * 0.95;

            $arr['gross_profit'] = (float)$arr['salesz_discount'] - (float)$arr['advertisingz'] - (float)$arr['freightmj'] - (float)$arr['material'];
            $arr['timedate'] = $lastmonth_start;
            $arr['total_price'] = $item['total_price'];
            $arr['accounturl'] = $item['accounturl'];
            $account = Db::name('fedition_reportmonthp')
                ->where('timedate',$arr['timedate'])
                ->where('accounturl',$arr['accounturl'])
                ->find();
            if (empty($account)) {
                $reportmonth = Db::name('fedition_reportmonthp')->insert($arr);
            }else{
                $reportmonth = Db::name('fedition_reportmonthp')
                    ->where('timedate',$arr['timedate'])
                    ->where('accounturl',$arr['accounturl'])
                    ->update($arr);
            }
        }

        //计算个人业绩
        $reportmonth = Db::name('fedition_reportmonthp')
            ->where('timedate',$lastmonth_start)
            ->select();
        if (!empty($reportmonth)) {
            Db::name('fedition_reportmonthtwop')
                ->where('timedate',$lastmonth_start)
                ->delete();
            foreach ($reportmonth as $arr) {
                unset($arr['id']);
                unset($arr['status']);
                $reportmonthtwo = Db::name('fedition_reportmonthtwop')
                    ->where('timedate',$arr['timedate'])
                    ->where('admin_id',$arr['admin_id'])
                    ->find();
                if (empty($reportmonthtwo)) {
                    $arr['zcost'] = $arr['zcost'];
                    Db::name('fedition_reportmonthtwop')->insert($arr);
                }else{
                    $arr['freight'] = $reportmonthtwo['freight'] + $arr['freight'];
                    $arr['freightmj'] = $reportmonthtwo['freightmj'] + $arr['freightmj'];
                    $arr['material'] = $reportmonthtwo['material'] + $arr['material'];
                    $arr['zcost'] = $reportmonthtwo['zcost'] + $arr['zcost'];
                    $arr['salesz'] = $reportmonthtwo['salesz'] + $arr['salesz'];
                    $arr['salesz_discount'] = $arr['salesz'] * 0.95;
                    $arr['gross_profit'] = $reportmonthtwo['gross_profit'] + $arr['gross_profit'];
                    $arr['total_price'] = $reportmonthtwo['total_price'] + $arr['total_price'];
                    $arr['advertisingz'] = $reportmonthtwo['advertisingz'] + $arr['advertisingz'];
                    Db::name('fedition_reportmonthtwop')
                        ->where('timedate',$arr['timedate'])
                        ->where('admin_id',$arr['admin_id'])
                        ->update($arr);
                }
            }
        }
        if(!empty($reportmonth)){
            $this->success('操作成功',$reportmonth);
        } else {
            $this->error('未找到相关订单');
        }
    }
    /**
     *5分钟更新一次订单
     * 订单信息 https://developer.myshoplaza.com/openapi/2020-07/orders
     * 商品详情 同上接口 line_item字段
     * 运单号详情 https://developer.myshoplaza.com/openapi/2020-07/orders/{order_id}/fulfillments
     * 商品附带SKU (先查商品详情-找到SKU列表-找到成本) https://developer.myshoplaza.com/openapi/2020-07/products/{product_id}
     */
    public function updateordertime($id = null)
    {
        if (!empty($id)) {
            $ordershopify = Db::name('fedition_ordershoplaza')
                ->where('id',$id)
                ->select();
        }else {
            $ids = $this->request->request('ids');
            $type = $this->request->request('type');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            }
            if ($type == 2) {
                $where['updateordertime'] = '';
            }
            $ordershopify = Db::name('fedition_ordershoplaza')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('30')
                ->select();
        }
        if (!empty($ordershopify)) {
            foreach ($ordershopify as $t) {
                $accountur = Db::name('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                if (empty($accountur['shoplazaname'])) {
                    continue;
                }
                $url = $accountur['shoplazaname'] . "/openapi/2020-07/orders/" . $t['id'];
                $data = $this->geturl($url,$accountur['shoplazatoken']);
                $data = json_decode($data, true);
                $row = array();
                if (isset($data['order'])) {
                    //新增商品物流单
//                    $url2 = $accountur['shoplazaname'] . "/openapi/2020-07/orders/" . $t['id'] . "/fulfillments";
//                    $data2 = $this->geturl($url2,$accountur['shoplazatoken']);
//                    $data2 = json_decode($data2, true);
                    if (isset($data['order']['fulfillments'])) {
                        $fulfillments = $data['order']['fulfillments'];
                        if (!empty($fulfillments)) {
                            Db::name('fedition_orderfulfillmentsp')
                                ->where('order_id', $t['id'])
                                ->delete();
                            foreach ($fulfillments as $line_item) {
                                $arr2['tracking_number'] = $line_item['tracking_number'];
                                $arr2['tracking_company'] = $line_item['tracking_company'];
                                $arr2['order_id'] = $line_item['order_id'];
                                $arr2['fulfillment_id'] = $line_item['id'];
                                $arr2['createtime'] = time();
                                $arr2['updatetime'] = time();
                                Db::name('fedition_orderfulfillmentsp')->insert($arr2);
                            }
                        }
                    }
                    //新增商品详情
                    if (isset($data['order']['line_items'])) {
                        $line_items = $data['order']['line_items'];
                        if (!empty($line_items)) {
                            foreach ($line_items as $line_item) {
                                $arr['sku'] = $line_item['sku'];
                                $arr['title'] = $line_item['product_title'];
                                $arr['product_id'] = $line_item['product_id'];
                                $arr['variant_id'] = $line_item['variant_id'];
                                $arr['variant_title'] = $line_item['variant_title'];
                                $arr['quantity'] = $line_item['quantity'];
                                $arr['order_id'] = $t['id'];
                                $arr['createtime'] = time();
                                $arr['updatetime'] = time();
                                $arr['order_time'] = $t['created_at'];
                                $orderquantity = Db::name('fedition_orderquantityp')
                                    ->where('variant_id', $arr['variant_id'])
                                    ->where('order_id', $arr['order_id'])
                                    ->find();
                                if (empty($orderquantity)) {
                                    Db::name('fedition_orderquantityp')->insert($arr);
                                }
                                //商品记录
                                $orderproduct = Db::name('fedition_orderproductp')->where('product_id', $arr['product_id'])->find();
                                if (empty($orderproduct)) {
                                    $product['createtime'] = time();
                                    $product['product_id'] = $arr['product_id'];
                                    $product['accounturl'] = $t['accounturl'];
                                    $product['product_name'] = $arr['title'];
                                    Db::name('fedition_orderproductp')->insert($product);
                                }
                                //如果sku库没有则添加
                                if (!empty($arr['variant_id'])) {
                                    $ordersku = Db::name('fedition_orderskup')
                                        ->where('variants_id', $arr['variant_id'])
                                        ->find();
                                    if (empty($ordersku)) {
                                        $sku_arr['product_id'] = $arr['product_id'];
                                        $sku_arr['createtime'] = time();
                                        $sku_arr['updatetime'] = time();
                                        $sku_arr['variants_id'] = $arr['variant_id'];
                                        $sku_arr['sku'] = $arr['sku'];
                                        $sku_arr['material'] = 0;
                                        $sku_arr['accounturl'] = $t['accounturl'];
                                        Db::name('fedition_orderskup')
                                            ->insert($sku_arr);
                                    }
                                }
                            }
                        }
                    }
                    $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    //实时更新订单状态
                    $row['order_status'] = $data['order']['status'];
                    $row['refund_status'] = $data['order']['refund_status'];
                    $row['fulfillment_status'] = $data['order']['fulfillment_status'];
                    $row['financial_status'] = $data['order']['financial_status'];
                    if (isset($data['order']['customer']['email'])) {
                        $row['email'] = $data['order']['customer']['email'];
                    }
                    if (isset($data['order']['shipping_address']['name'])) {
                        $row['shipping_name'] = $data['order']['shipping_address']['name'];
                    }
                    if (isset($data['order']['shipping_address']['phone'])) {
                        $row['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "",$data['order']['shipping_address']['phone']);
                    }
                    if (isset($data['order']['shipping_address']['city'])) {
                        $row['city'] = $data['order']['shipping_address']['city'];
                    }
                    if (isset($data['order']['shipping_address']['address1'])) {
                        $row['address1'] = $data['order']['shipping_address']['address1'];
                    }
                    if (isset($data['order']['shipping_address']['country_code'])) {
                        $row['country_code'] = $data['order']['shipping_address']['country_code'];
                    }
                    $row['total_price'] = $data['order']['total_price'];

                }
                $row['updateordertime'] = time();
                //本次新增几个字段
                Db::name('fedition_ordershoplaza')
                    ->where('id', $t['id'])
                    ->update($row);
                //发送短信
//                $this->ordershoplazasms($data['order'],2);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    //发送短信
    //$type 1创建了订单 2更新了订单 3支付后发送短信
    public function ordershoplazasms($data,$type)
    {
        if ($type == 1) {
            $addsms['type'] = 1;
            $addsms['order_id'] = $data['id'];
            $addsms['createtime'] = strtotime($data['created_at']);
            $addsms['msg'] = '创建了订单';
            $addsms['status'] = 'normal';
            Db::name('fedition_ordershoplazasms')->insert($addsms);
        }elseif($type == 2){
            //已发货状态
            $addsms2['type'] = 2;
            $addsms2['order_id'] = $data['id'];
            $addsms2['createtime'] = strtotime($data['updated_at']);

            $wheresms2['order_id'] = $data['id'];
            $wheresms2['type'] = 2;
            $wheresms2['status'] = 'normal';
            $ordershoplazasm2 = Db::name('fedition_ordershoplazasms')->where($wheresms2)->find();
            if (empty($ordershoplazasm2) && $data['fulfillment_status'] == 'finished' && $addsms2['createtime'] >= 1640765038) {
                //方便测试，12/19号之前的订单不发送短信
                if (isset($data['shipping_address']['phone']) && !empty($data['shipping_address']['phone']) && isset($data['shipping_address']['country_code']) && !empty($data['shipping_address']['country_code'])) {
                    $addsms2['mobile'] = $data['shipping_address']['phone'];
                    $country2 = $data['shipping_address']['country_code'];
                    //关闭短信接口
                    //$return_data2 = array();
                    $return_data2 = $this->clicksend_send($addsms2['mobile'],$country2,$wheresms2['type']);
                    if (!empty($return_data2)) {
                        $addsms2['msg'] = $return_data2['response_msg'];
                        if ($return_data2['http_code'] == 200) {
                            $addsms2['status'] = 'normal';
                        } else {
                            $addsms2['status'] = 'hidden';
                        }
                    } else {
                        $addsms2['msg'] = '接口数据为空';
                    }
                }else{
                    $addsms2['msg'] = '客户联系方式或者国家代码为空';
                }
                Db::name('fedition_ordershoplazasms')->insert($addsms2);
            }

            //已支付状态
            $addsms['type'] = 3;
            $addsms['order_id'] = $data['id'];
            $addsms['createtime'] = strtotime($data['updated_at']);

            $wheresms['order_id'] = $data['id'];
            $wheresms['type'] = 3;
            $wheresms['status'] = 'normal';
            $ordershoplazasm = Db::name('fedition_ordershoplazasms')->where($wheresms)->find();
            if (empty($ordershoplazasm) && $data['financial_status'] == 'paid' && $addsms['createtime'] >= 1640765038) {
                //方便测试，12/19号之前的订单不发送短信
                if (isset($data['shipping_address']['phone']) && !empty($data['shipping_address']['phone']) && isset($data['shipping_address']['country_code']) && !empty($data['shipping_address']['country_code'])) {
                    $addsms['mobile'] = $data['shipping_address']['phone'];
                    $country = $data['shipping_address']['country_code'];
                    //关闭短信接口
                    //$return_data = array();
                    $return_data = $this->clicksend_send($addsms['mobile'],$country,$wheresms['type']);
                    if (!empty($return_data)) {
                        $addsms['msg'] = $return_data['response_msg'];
                        if ($return_data['http_code'] == 200) {
                            $addsms['status'] = 'normal';
                        } else {
                            $addsms['status'] = 'hidden';
                        }
                    } else {
                        $addsms['msg'] = '接口数据为空';
                    }
                }else{
                    $addsms['msg'] = '客户联系方式或者国家代码为空';
                }
                Db::name('fedition_ordershoplazasms')->insert($addsms);
            }

            //部分发货状态
            $addsms4['type'] = 4;
            $addsms4['order_id'] = $data['id'];
            $addsms4['createtime'] = strtotime($data['updated_at']);

            $wheresms4['order_id'] = $data['id'];
            $wheresms4['type'] = 4;
            $wheresms4['status'] = 'normal';
            $ordershoplazasm4 = Db::name('fedition_ordershoplazasms')->where($wheresms4)->find();
            if (empty($ordershoplazasm4) && $data['fulfillment_status'] == 'partially_shipped' && $addsms4['createtime'] >= 1640765038) {
                //方便测试，12/19号之前的订单不发送短信
                if (isset($data['shipping_address']['phone']) && !empty($data['shipping_address']['phone']) && isset($data['shipping_address']['country_code']) && !empty($data['shipping_address']['country_code'])) {
                    $addsms4['mobile'] = $data['shipping_address']['phone'];
                    $country4 = $data['shipping_address']['country_code'];
                    //关闭短信接口
                    //$return_data4 = array();
                    $return_data4 = $this->clicksend_send($addsms4['mobile'],$country4,$wheresms4['type']);
                    if (!empty($return_data4)) {
                        $addsms4['msg'] = $return_data4['response_msg'];
                        if ($return_data4['http_code'] == 200) {
                            $addsms4['status'] = 'normal';
                        } else {
                            $addsms4['status'] = 'hidden';
                        }
                    } else {
                        $addsms4['msg'] = '接口数据为空';
                    }
                }else{
                    $addsms4['msg'] = '客户联系方式或者国家代码为空';
                }
                Db::name('fedition_ordershoplazasms')->insert($addsms4);
            }
            //结束部分发货状态

        }
    }

    /**
     * 检查店铺是否正常
     */
    public function isnormal()
    {
        $iscustom = Db::name('fedition_accounturl')
            ->where('iscustom_shoplaza',1)
//            ->where('status','normal')
            ->select();
        $result = array();
        if($iscustom){
            foreach ($iscustom as $k => $v) {
                $result[] = $this->store_isnormal($v);
            }
        }
        $this->success('操作成功',$result);
    }

    public function store_isnormal($iscustom)
    {
        $url = $iscustom['shoplazaname']."/openapi/2020-07/shop";
        $data = $this->geturl($url,$iscustom['shoplazatoken']);
        $result = array();
        if($data){
            $data = json_decode($data,true);
            if (!empty($data['error'])) {
                if ($data['error'] == 'store is not active') {
                    //如果门店不可用，则报警
                    $result = $this->unavailable($iscustom);
                    return $result;
                }
            }else{
                if ($iscustom['status'] == 'unavailable') {
                    //恢复
                    $result =  Db::name('fedition_accounturl')
                        ->where('id',$iscustom['id'])
                        ->update(
                            [
                                'status' => 'normal',
                                'updateordertimec' => time(),
                            ]
                        );
                }
                return $result;
            }
        }
    }

    public function unavailable($iscustom)
    {
//        $params['mobile'] = '16607234106';
//        $smsbao = new smsbao();
//        $result = $smsbao->mobile($params['mobile'])->msg("您的店铺".$iscustom['name']."已下线，请尽快查看并处理")->send();
//        if ($result) {
       $return =  Db::name('fedition_accounturl')
            ->where('id',$iscustom['id'])
            ->update(
                [
                    'status' => 'unavailable',
                    'updateordertimec' => time(),
                ]
            );
//        }
        return $return;
    }

    function geturl($url,$token){
        $headerArray = array("Content-Type: application/json;",'Access-Token: '.$token);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl($url,$data = array(),$token){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type: application/json;",'Access-Token: '.$token);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function puturl($url,$data = array(),$token){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type: application/json;",'Access-Token: '.$token);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function fedition_shoplazacheck()
    {
        $shoplazacheck = Db::name('fedition_shoplazacheck')
            ->order('updatetime asc')
            ->where('status','hidden')
            ->limit('100')
            ->select();
        foreach ($shoplazacheck as $check) {
            $update = array();
            $ordershoplaza = Db::name('fedition_ordershoplaza')->where('transaction_no',$check['transaction_no'])->find();
            if (!empty($ordershoplaza)) {
                $orderfulfillmentsp = Db::name('fedition_orderfulfillmentsp')->where('order_id',$ordershoplaza['id'])->find();
                if (!empty($orderfulfillmentsp)) {
                    $update['tracking_number'] = $orderfulfillmentsp['tracking_number'];
                    $update['status'] = 'normal';
                }
            }
            $update['updatetime'] = time();
            Db::name('fedition_shoplazacheck')->where('id',$check['id'])->update($update);
        }
        $this->success('操作成功');
    }

    public function cancel_order($id)
    {
        $info = array();
        $ordershoplaza = Db::name('fedition_ordershoplaza')->where('id',$id)->find();
        $accounturl = Db::name('fedition_accounturl')->where('id',$ordershoplaza['accounturl'])->find();
        $url = $accounturl['shoplazaname'] . "/openapi/2020-07/orders/" . $id."/cancel";
        $info['id'] = $id;
        $data = $this->posturl($url,$info,$accounturl['shoplazatoken']);
        $data = json_decode($data, true);
        return $data;
    }

    public function refund_order($id)
    {
        $info = array();
        $ordershoplaza = Db::name('fedition_ordershoplaza')->where('id',$id)->find();
        $accounturl = Db::name('fedition_accounturl')->where('id',$ordershoplaza['accounturl'])->find();
        $url = $accounturl['shoplazaname'] . "/openapi/2020-07/orders/" . $id."/refund";
        $info['id'] = $id;
        $data = $this->posturl($url,$info,$accounturl['shoplazatoken']);
        $data = json_decode($data, true);
        return $data;
    }

    public function fulfillments_order($id = null)
    {
        if (!empty($id)) {
            $orderfulfillmentspz = Db::name('fedition_orderfulfillmentspz')
                ->where('id',$id)
                ->select();
        }else {
            $ids = $this->request->request('ids');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            }
            $where['status'] = 'hidden';
            $orderfulfillmentspz = Db::name('fedition_orderfulfillmentspz')
                ->order('updateordertime asc')
                ->where($where)
                ->limit('30')
                ->select();
        }
        if (!empty($orderfulfillmentspz)) {
            foreach ($orderfulfillmentspz as $t) {
                $row = array();
                $row['status'] = 'hidden';
                if (!empty($t['ytracking_number']) && !empty($t['tracking_number'])) {
                    $new_orderfulfillmentsp = Db::name('fedition_orderfulfillmentsp')->where('tracking_number', $t['tracking_number'])->find();
                    if (!empty($new_orderfulfillmentsp)) {
                        $row['msg'] = '已转单';
                        $row['status'] = 'normal';
                    }else{
                        $orderfulfillmentsp = Db::name('fedition_orderfulfillmentsp')->where('tracking_number', $t['ytracking_number'])->find();
                        if (!empty($orderfulfillmentsp)) {
                            $ordershoplaza = Db::name('fedition_ordershoplaza')->where('id', $orderfulfillmentsp['order_id'])->find();
                            $accounturl = Db::name('fedition_accounturl')
                                ->where('id', $ordershoplaza['accounturl'])
                                ->find();
                            if (!empty($orderfulfillmentsp['order_id']) && !empty($orderfulfillmentsp['fulfillment_id'])) {
                                $url = $accounturl['shoplazaname'] . "/openapi/2020-07/orders/" . $orderfulfillmentsp['order_id']."/fulfillments/".$orderfulfillmentsp['fulfillment_id'];
                                $post = array();
                                $post['tracking_number'] = $t['tracking_number'];
                                $data = $this->puturl($url,$post,$accounturl['shoplazatoken']);
                                $data = json_decode($data, true);
                                if (!empty($data['errors'])) {
                                    $row['msg'] = $data['errors'][0];
                                }else{
                                    $row['msg'] = '更换成功';
                                    $row['status'] = 'normal';
                                }
                            }else{
                                $row['msg'] = '物流id：'.$orderfulfillmentsp['id'].'订单号或物流id为空';
                            }
                        }else{
                            $row['msg'] = '找不到该物流单';
                        }
                    }
                }else{
                    $row['msg'] = '转单号信息为空';
                }
                $row['updateordertime'] = time();
                //本次新增几个字段
                Db::name('fedition_orderfulfillmentspz')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功');
        } else {
            $this->error('未找到相关订单');
        }
    }

    //店铺详情
    public function shopinfo()
    {
        $iscustoms = Db::name('fedition_accounturl')
            ->select();
        if (!empty($iscustoms)) {
            foreach ($iscustoms as $iscustom) {
                $url = $iscustom['shoplazaname']."/openapi/2020-07/shop";
                $data = $this->geturl($url,$iscustom['shoplazatoken']);
                $data = json_decode($data, true);
                if (!empty($data)) {
                    if (empty($data['error'])) {
                        $shop = array();
                        if (isset($data['shop']['name'])) {
                            $shop['name'] = $data['shop']['name'];
                        }
                        if (isset( $data['shop']['domain'])) {
                            $shop['url'] = $data['shop']['domain'];
                        }
                        $shop['updateordertime'] = time();
                        $returns = Db::name('fedition_accounturl')
                            ->where('id',$iscustom['id'])
                            ->update($shop);
                    }
                }
            }
            $this->error('操作完成',$returns);
        } else {
            $this->error('暂无数据');
        }
    }

    /**
     * orderproduct 新增商品对应的sku列表
     * read_products权限
     * read_inventory权限要开通
     */
    public function addorderproduct($product_id = null)
    {
        if (!empty($product_id)) {
            $orderproduct = Db::name('fedition_orderproductp')->where('product_id',$product_id)->order('producttime asc')->select();
        } else {
            $type = $this->request->request('type');
            $orderproduct = Db::name('fedition_orderproductp')
                ->where('isproduct',$type)
                ->where('product_id','>','0')
                ->order('producttime asc')
                ->limit(100)->select();
        }
        if (!empty($orderproduct)) {
            foreach ($orderproduct as $item) {
                $shopify = $this->add_orderproduct($item);
            }
            $this->success('操作成功',$shopify);
        } else {
            if (empty($product_id)) {
                //            未找到相关订单
                $this->error('未找到相关订单');
            }
        }
    }

    public function add_orderproduct($ordershopify)
    {
        $iscustom = Db::name('fedition_accounturl')
            ->where('id',$ordershopify['accounturl'])
            ->find();
        $url = $iscustom['shoplazaname']."/openapi/2020-07/products/".$ordershopify['product_id'];
        $data = $this->geturl($url,$iscustom['shoplazatoken']);
        $data = json_decode($data, true);
        $arr['errors'] = '';
        if($data) {
            if (!empty($data['errors'])) {
                $arr['isproduct'] = 3;
                $arr['errors'] = $data['errors'][0];
            }elseif(!empty($data['error'])) {
                $arr['isproduct'] = 5;
                $arr['errors'] = $data['error'];
            } else {
                if (isset($data['product']['image']['src']) && !empty($data['product']['image']['src'])) {
                    $arr['isproduct'] = 1;
                    $arr['src'] = $data['product']['image']['src'];
                }else{
                    $arr['isproduct'] = 4;//无属性
                }
            }
        }else{
            $arr['isproduct'] = 2;
        }
        $arr['producttime'] = time();
        $shopify = Db::name('fedition_orderproductp')->where('id',$ordershopify['id'])->update($arr);
        return $shopify;
    }

    //测试变体详情
    public function variantsinfo()
    {
        $iscustoms = Db::name('fedition_accounturl')
            ->where('id',41)
            ->select();
        if (!empty($iscustoms)) {
            foreach ($iscustoms as $iscustom) {
                $url = $iscustom['shoplazaname']."/openapi/2020-07/variants/9f97b932-b16c-4fa7-9718-5833c5a5107f";
                $url = $iscustom['shoplazaname']."/openapi/2020-07/products/e0b975f4-95e7-48e0-9de1-d2b155d41c71";
                $data = $this->geturl($url,$iscustom['shoplazatoken']);
                $data = json_decode($data, true);
                dump($data);die;
            }
            $this->error('操作完成',$returns);
        } else {
            $this->error('暂无数据');
        }
    }

    //查看账户详情
    public function clicksend_account()
    {
        $url = 'https://rest.clicksend.com/v3/account';
        $iscustom['apikey'] = 'nocredit';
        $iscustom['secretapikey'] = 'D83DED51-9E35-4D42-9BB9-0E34B7CA85AE';
//        $data = $this->geturl_clicksend($url,$iscustom);
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }

    //查看您的号码
    public function clicksend_numbers()
    {
        $url = 'https://rest.clicksend.com/v3/numbers';
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }

    //查看您的号码
    public function clicksend_send($mobile = null,$country,$type)
    {
        $msgx = array();
        $smsconfig = Db::name('fedition_smsconfig')->where('type',$type)->order('id asc')->find();
        if (!empty($smsconfig)) {
            $msgx['body'] = $smsconfig['body'];
//            $msgx['country'] = $smsconfig['country'];
//            $msgx['to'] = $smsconfig['mobile'];
        } else {
            $msgx['body'] = '订单支付成功';
//            $msgx['country'] = 'US';
//            $msgx['to'] = '(937)462-0674';
        }
        $url = 'https://rest.clicksend.com/v3/sms/send';
        $msgx['country'] = $country;
        $msgx['to'] = $mobile;
        $msgx['source'] = 'php';
        $msgx['from'] = 'company';
        $messages[] = $msgx;
        $msg['messages'] = $messages;
        $data = $this->posturl_clicksend($url,$msg,$this->iscustom);
        $data = json_decode($data, true);
        return $data;
//        if ($data['http_code'] == 200) {
//            $this->success('接口成功',$data['response_msg']);
//        } else {
//            $this->error('接口失败',$data['response_msg']);
//        }
    }


    //直接发送短信
    public function test_send()
    {
        $msgx = array();
        $url = 'https://rest.clicksend.com/v3/sms/send';
        $msgx['body'] = '测试号码跟区号';
        $msgx['to'] = '+61448918791';
        $msgx['source'] = 'php';
        $msgx['from'] = 'company';
        $messages[] = $msgx;
        $msg['messages'] = $messages;
        $data = $this->posturl_clicksend($url,$msg,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
    }

    //查看短信历史记录
    public function clicksend_smshistory()
    {
        $url = 'https://rest.clicksend.com/v3/sms/history';
        $before_ordershopify = Db::name('fedition_ordershoplazasmshistory')
            ->order('date desc')
            ->where('date','>=',1640765038)
            ->find();
        if (!empty($before_ordershopify)) {
            $created_at_max = $before_ordershopify['date'];
        }else{
            $created_at_max = '1640765038';
        }
        $limit = 20;
        $url = $url.'?date_from='.$created_at_max.'&page=1&limit='.$limit;
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        if (!empty($data)) {
            if ($data['http_code'] == 200) {
                $history = $data['data']['data'];
                $historys = array();
                foreach ($history as $item) {
                    $ordershoplazasmshistory = Db::name('fedition_ordershoplazasmshistory')->where('message_id', $item['message_id'])->find();
                    if (!empty($ordershoplazasmshistory)) {
                        $historys[] = '重复';
                    } else {
                        $arr['status'] = $item['status'];
                        $arr['date'] = $item['date'];
                        $arr['from'] = $item['from'];
                        $arr['to'] = $item['to'];
                        $arr['body'] = $item['body'];
                        $arr['status_text'] = $item['status_text'];
                        $arr['message_id'] = $item['message_id'];
                        $arr['message_parts'] = $item['message_parts'];
                        $arr['message_price'] = $item['message_price'];
                        $arr['country'] = $item['country'];
                        $historys[] = Db::name('fedition_ordershoplazasmshistory')->where('message_id', $item['message_id'])->insert($arr);
                    }
                }
                $this->success('完成操作',$historys);
            } else {
                $this->error('接口错误',$data['response_msg']);
            }
        } else {
            $this->error('接口无数据');
        }
    }

    //查看国家
    public function clicksend_countries()
    {
        $url = 'https://rest.clicksend.com/v3/countries';
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }
    //查看所有交易
    public function recharge_transactions()
    {
        $url = 'https://rest.clicksend.com/v3/recharge/transactions';
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }
    //计算电子邮件价格
    public function email_price()
    {
        $url = 'https://rest.clicksend.com/v3/email/price';
        $data = $this->geturl_clicksend($url,$this->iscustom);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }
    public function geturl_clicksend($url,$iscustom){
        $apikey = $iscustom['apikey'];
        $secretapikey = $iscustom['secretapikey'];
        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl_clicksend($url,$data = array(),$iscustom=null){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['apikey'];
        $secretapikey = $iscustom['secretapikey'];

        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //新增转单号
    public function fedition_ordertransfert()
    {
        $return = array();
        $ordertransfert = Db::name('fedition_ordertransfert')
            ->where('status', 'hidden')
            ->order('updatetime asc')
            ->limit('500')
            ->select();
        if (!empty($ordertransfert)) {
            foreach ($ordertransfert as $item) {
                $update = array();
                $ordertransfer = Db::name('fedition_ordertransfer')->where('transfer_number', $item['z_number'])->find();
                if (!empty($ordertransfer)) {
                    $arr = array();
                    $arr['transfer_number'] = $item['transfer_number'];
                    $arr['freight'] = $ordertransfer['freight'];
                    $arr['transfer_id'] = 353;
                    $arr['status'] = $ordertransfer['status'];
                    $return_ordertransfer1 = Db::name('fedition_ordertransfer')->where('transfer_number',$arr['transfer_number'])->find();
                    if (empty($return_ordertransfer1)) {
                        $return_ordertransfer = Db::name('fedition_ordertransfer')->insert($arr);
                        if (!empty($return_ordertransfer)) {
                            $update['status'] = 'normal';
                        }
                    }
                }
                $update['updatetime'] = time();
                $return = Db::name('fedition_ordertransfert')->where('id', $item['id'])->update($update);
            }
        }
        $this->success('成功',$return);
    }

    //新增转单号
    public function fedition_ordertransferts()
    {
        $return = array();
        $ordertransfert = Db::name('fedition_ordertransferts')
            ->where('status', 'hidden')
            ->order('updatetime asc')
            ->limit('500')
            ->select();
        if (!empty($ordertransfert)) {
            foreach ($ordertransfert as $item) {
                $update = array();
                $ordertransfer = Db::name('fedition_ordertransfert')->where('transfer_number', $item['transfer_number'])->find();
                if (!empty($ordertransfer)) {
                    $update['z_number'] = $ordertransfer['z_number'];
                    $update['status'] = 'normal';
                }
                $update['updatetime'] = time();
                $return = Db::name('fedition_ordertransferts')->where('id', $item['id'])->update($update);
            }
        }
        $this->success('成功',$return);
    }
}
